from flask import Blueprint, request, jsonify
from flask_jwt_extended import create_access_token, create_refresh_token, jwt_required, get_jwt_identity
from app import db
from app.models import User
from datetime import datetime
import re

auth_bp = Blueprint('auth', __name__)

@auth_bp.route('/register', methods=['POST'])
def register():
    """用户注册"""
    data = request.get_json()
    
    if not data:
        return jsonify({'message': '请求数据不能为空'}), 400
    
    username = data.get('username')
    email = data.get('email')
    password = data.get('password')
    real_name = data.get('real_name', '')
    phone = data.get('phone', '')
    
    if not username or not email or not password:
        return jsonify({'message': '用户名、邮箱和密码不能为空'}), 400
    
    # 验证用户名格式
    if re.match(r'^[a-zA-Z0-9_]{3,20}$', username) is None:
        return jsonify({'message': '用户名格式不正确'}), 400
    
    # 验证邮箱格式
    if re.match(r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$', email) is None:
        return jsonify({'message': '邮箱格式不正确'}), 400
    
    # 验证密码长度
    if len(password) < 6:
        return jsonify({'message': '密码长度不能少于6位'}), 400
    
    # 检查用户名是否已存在
    if User.query.filter_by(username=username).first():
        return jsonify({'message': '用户名已存在'}), 400
    
    # 检查邮箱是否已存在
    if User.query.filter_by(email=email).first():
        return jsonify({'message': '邮箱已存在'}), 400
    
    user = User(
        username=username,
        email=email,
        real_name=real_name,
        phone=phone
    )
    user.password = password
    
    # 默认分配普通用户角色
    from app.models import Role
    user_role = Role.query.filter_by(code='user').first()
    if user_role:
        user.roles = [user_role]
    
    try:
        db.session.add(user)
        db.session.commit()
        return jsonify({'message': '注册成功，请登录'}), 201
    except Exception as e:
        db.session.rollback()
        return jsonify({'message': '注册失败'}), 500

@auth_bp.route('/login', methods=['POST'])
def login():
    """用户登录"""
    data = request.get_json()
    
    if not data:
        return jsonify({'message': '请求数据不能为空'}), 400
    
    username = data.get('username')
    password = data.get('password')
    
    if not username or not password:
        return jsonify({'message': '用户名和密码不能为空'}), 400
    
    # 验证用户名格式
    if re.match(r'^[a-zA-Z0-9_]{3,20}$', username) is None:
        return jsonify({'message': '用户名格式不正确'}), 400
    
    user = User.query.filter_by(username=username).first()
    
    if not user or not user.verify_password(password):
        return jsonify({'message': '用户名或密码错误'}), 401
    
    if not user.is_active:
        return jsonify({'message': '账户已被禁用'}), 401
    
    # 更新最后登录时间
    user.last_login = datetime.utcnow()
    db.session.commit()
    
    # 生成token
    access_token = create_access_token(identity=str(user.id))
    refresh_token = create_refresh_token(identity=str(user.id))
    
    return jsonify({
        'message': '登录成功',
        'access_token': access_token,
        'refresh_token': refresh_token,
        'user': user.to_dict()
    }), 200

@auth_bp.route('/refresh', methods=['POST'])
@jwt_required(refresh=True)
def refresh():
    """刷新token"""
    current_user_id = get_jwt_identity()
    new_access_token = create_access_token(identity=current_user_id)
    
    return jsonify({
        'access_token': new_access_token
    }), 200

@auth_bp.route('/profile', methods=['GET'])
@jwt_required()
def get_profile():
    """获取当前用户信息"""
    current_user_id = int(get_jwt_identity())
    user = User.query.get(current_user_id)
    
    if not user:
        return jsonify({'message': '用户不存在'}), 404
    
    return jsonify({
        'user': user.to_dict()
    }), 200

@auth_bp.route('/profile', methods=['PUT'])
@jwt_required()
def update_profile():
    """更新用户信息"""
    current_user_id = int(get_jwt_identity())
    user = User.query.get(current_user_id)
    
    if not user:
        return jsonify({'message': '用户不存在'}), 404
    
    data = request.get_json()
    
    if not data:
        return jsonify({'message': '请求数据不能为空'}), 400
    
    # 允许更新的字段
    allowed_fields = ['real_name', 'email', 'phone', 'avatar']
    
    for field in allowed_fields:
        if field in data:
            setattr(user, field, data[field])
    
    try:
        db.session.commit()
        return jsonify({
            'message': '更新成功',
            'user': user.to_dict()
        }), 200
    except Exception as e:
        db.session.rollback()
        return jsonify({'message': '更新失败'}), 500

@auth_bp.route('/change-password', methods=['POST'])
@jwt_required()
def change_password():
    """修改密码"""
    current_user_id = int(get_jwt_identity())
    user = User.query.get(current_user_id)
    
    if not user:
        return jsonify({'message': '用户不存在'}), 404
    
    data = request.get_json()
    
    if not data:
        return jsonify({'message': '请求数据不能为空'}), 400
    
    old_password = data.get('old_password')
    new_password = data.get('new_password')
    
    if not old_password or not new_password:
        return jsonify({'message': '旧密码和新密码不能为空'}), 400
    
    if not user.verify_password(old_password):
        return jsonify({'message': '旧密码错误'}), 400
    
    if len(new_password) < 6:
        return jsonify({'message': '新密码长度不能少于6位'}), 400
    
    user.password = new_password
    
    try:
        db.session.commit()
        return jsonify({'message': '密码修改成功'}), 200
    except Exception as e:
        db.session.rollback()
        return jsonify({'message': '密码修改失败'}), 500

@auth_bp.route('/permissions', methods=['GET'])
@jwt_required()
def get_user_permissions():
    """获取当前用户权限"""
    current_user_id = int(get_jwt_identity())
    user = User.query.get(current_user_id)
    
    if not user:
        return jsonify({'message': '用户不存在'}), 404
    
    # 获取用户所有角色的权限
    permissions = set()
    for role in user.roles:
        for permission in role.permissions:
            permissions.add(permission.code)
    
    return jsonify({
        'permissions': list(permissions)
    }), 200

@auth_bp.route('/menus', methods=['GET'])
@jwt_required()
def get_user_menus():
    """获取当前用户菜单（树形结构）"""
    current_user_id = int(get_jwt_identity())
    user = User.query.get(current_user_id)
    
    if not user:
        return jsonify({'message': '用户不存在'}), 404
    
    # 获取用户所有角色的菜单ID
    menu_ids = set()
    for role in user.roles:
        for menu in role.menus:
            menu_ids.add(menu.id)
    
    # 获取用户有权限的顶级菜单（parent_id 为 NULL）
    from app.models import Menu
    user_menus = Menu.query.filter(
        Menu.parent_id.is_(None),
        Menu.id.in_(menu_ids),
        Menu.is_active == True
    ).order_by(Menu.sort_order.asc(), Menu.id.asc()).all()
    
    # 构建树形结构
    tree_menus = []
    for menu in user_menus:
        # 递归获取子菜单
        def get_menu_with_children(menu_obj):
            menu_dict = menu_obj.to_dict(include_children=False)
            # 检查子菜单是否在用户权限中
            children = []
            for child in menu_obj.children:
                if child.id in menu_ids and child.is_active:
                    children.append(get_menu_with_children(child))
            menu_dict['children'] = children
            return menu_dict
        
        tree_menus.append(get_menu_with_children(menu))
    
    return jsonify({
        'menus': tree_menus
    }), 200 